package xim

import (
	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 获取我和其他人的聊天窗详情
//
//	uid	用户ID
//	tid	目标用户ID
func GetUserChat(uid uint, tid uint) (*Chat, error) {
	chat := Chat{}
	// cache_key := xcache.Key("xim.get.user.chat", uid, tid)
	// if xcache.Exists(cache_key) {
	// 	if err := xcache.GetStruct(cache_key, &chat); err == nil {
	// 		return &chat, nil
	// 	}
	// }
	type temp_struct struct {
		Count  int64  `gorm:"column:count"`
		ChatId uint64 `gorm:"column:chat_id"`
	}
	temp := temp_struct{}
	err := sql.RunNameReplaceScan("sql/get-user-chat", sqlRep(0), sqlRep(1), &temp, uid, tid)
	if err != nil {
		return nil, err
	}
	// 获取该群的详情信息
	if temp.ChatId == 0 {
		// 该聊天记录不存在，需要进行创建
		CreateUserChat(uid, tid)
	}
	// 获取聊天详情信息
	err = sql.RunNameReplaceScan("sql/get-user-chat", sqlRep(0), sqlRep(1), &temp, uid, tid)
	if err != nil {
		return nil, err
	}
	chats, err := GetChat(temp.ChatId)
	if err != nil {
		return nil, err
	}
	chat = *chats
	// 获取聊天群成员
	_, users, err := GetChatUser(chat.Id, 0, -1)
	if err != nil {
		return nil, err
	}
	if len(users) != 2 {
		return nil, xerror.New("聊天/群成员数量错误")
	}
	for i := 0; i < len(users); i++ {
		c := chat
		c.Name = users[i].Nickname
		c.Thumb = users[i].Thumb
		if users[i].UserId == uid {
			xcache.SetStruct(xcache.Key("xim.get.user.chat", tid, uid), c)
		} else {
			chat.Name = users[i].Nickname
			chat.Thumb = users[i].Thumb
			xcache.SetStruct(xcache.Key("xim.get.user.chat", uid, tid), c)
		}
	}
	return &chat, nil
}
